package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.common.utils.BeanUtils;
import com.atguigu.spzx.manager.mapper.SysMenuMapper;
import com.atguigu.spzx.manager.modules.utils.MenuHelper;
import com.atguigu.spzx.manager.entity.SysMenu;
import com.atguigu.spzx.manager.service.SysMenuService;
import com.atguigu.spzx.common.result.ResultCodeEnum;
import com.atguigu.spzx.manager.vo.sysMenu.SysMenuQueryRespVo;
import com.atguigu.spzx.manager.vo.sysMenu.SysMenuQueryTreeVo;
import com.atguigu.spzx.manager.vo.sysMenu.SysMenuSaveReqVo;
import com.atguigu.spzx.manager.vo.sysMenu.SysMenuUpdateReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * SysMenuService
 * </p>
 *
 * @author flyduck
 * @since 2023/10/25
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 菜单列表（树形）
     * @return
     */
    @Override
    public List<SysMenuQueryTreeVo> getMenuTree() {
        //获取所有菜单
        List<SysMenu> sysMenuList = sysMenuMapper.selectList(null);
        List<SysMenuQueryTreeVo> sysMenuQueryTreeRespVoList = BeanUtils.toBeanList(sysMenuList, SysMenuQueryTreeVo.class);
        //将菜单转换成要求的格式
        List<SysMenuQueryTreeVo> resultList = MenuHelper.buildTree(sysMenuQueryTreeRespVoList);
        return resultList;
    }

    /**
     * 添加菜单
     * @param reqVo
     * @return
     */
    @Override
    public void saveMenu(SysMenuSaveReqVo reqVo) {
        SysMenu sysMenu = BeanUtils.toBean(reqVo, SysMenu.class);
        sysMenuMapper.insert(sysMenu);
    }

    /**
     * 根据id查询菜单
     * @param id
     * @return
     */
    @Override
    public SysMenuQueryRespVo getMenuById(Long id) {
        SysMenu sysMenu = sysMenuMapper.selectById(id);
        SysMenuQueryRespVo respVo = BeanUtils.toBean(sysMenu, SysMenuQueryRespVo.class);
        return respVo;
    }

    /**
     * 修改菜单
     * @param reqVo
     * @return
     */
    @Override
    public void updateMenuById(SysMenuUpdateReqVo reqVo) {
        SysMenu sysMenu = BeanUtils.toBean(reqVo, SysMenu.class);
        sysMenuMapper.updateById(sysMenu);
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    @Override
    public void deleteMenuById(Long id) {
        //查询当前菜单下面是否有菜单
        Integer count = sysMenuMapper.getMenuCountByParentId(id);
        if (count > 0) {
            throw new GuiguException(ResultCodeEnum.NODE_ERROR);
        }
        sysMenuMapper.deleteById(id);
    }
}
